<?php
/**
 * 订单生成及相关
 * todo: 订单生成自需求汇总，若订单审批不通过，订单数据是自动退回汇总，还是手动切换？
 */
class indentController extends baseController {
	/**
	 * 从需求里生成采购订单
	 */
    public function gen(){
		$indent_id = fetch_a_int('indent-id');
		if($indent_id){ 
			//修改采购订单
			$indent = $this->indentCanbeModify($indent_id);
			$items = IndentItems::getByIndent($indent_id);
			$this->assign('stuffs', $items);
			$this->assign('indent', $indent);
			$this->assign('ismodify', true);
			$id = $indent['summary_id'];
//			Debug::pre(DemandHelper::getItemsByIndent($indent_id));
		}
		else{
			//从需求汇总里生成订单
			$id = fetch_a_int('id');
			if(!$id){
				return $this->get_summary_list();
			}
		}
		
		$summary = Summary::get($id);
		if(!$summary){
			Show::warn('此采购需求汇总记录不存在');
		}
		$this->assign('summary', $summary);
		$items = SummaryItemsHelper::getBySummaryToIndent($id);
		$this->assign('items', $items);
		$this->display();
	}
	
	private function indentCanbeModify($indent_id){
		$indent = Indent::get($indent_id);
		if(!$indent){
			Show::warn('无此订单记录');
		}
		if($indent['user_id']!=UID){
			Show::warn('只创建者有权修改订单记录');
		}
		if($indent['audit_flow']!=Reviewer::AUDIT_FAIL){
			Show::warn('无法修改');
		}
		return $indent;
	}

	/**
	 * 显示汇总需求列表
	 */
	protected function get_summary_list(){
		$list = SummaryHelper::getList(array('flow'=>0), 0,0, 'flow ASC,addtime DESC');
		$this->assign('list', $list);
		$this->display('indent-get_summary_list');
	}

	/**
	 * 保存订单
	 */
	public function save(){
		
		$id = fetch_a_int('id');
		if(!$id){
			Show::warn('无此记录');
		}

		$tmp = array_diff(array_map('intval', fetch_a_array('ware_id')), array(0));
		if(!$tmp){
			Show::warn('请选择至少一项材料信息');
		}

		$ware_remarks = fetch_a_array('wremark');

		$wares = SummaryItemsHelper::getBySummaryToIndent($id, array('ware_id','IN',$tmp));

		/**
		 * 订单所属部门应该是当前制作人的部门，因需求本身已被打乱到汇总表；
		 * 这里的部门是用于部门审批(采购订单审批)之用；
		 */
		$dept_id = UserAuthHelper::deptid();

		$total = 0.0;
		$supplier_id = 0;
		foreach($wares as $ware){
			if(!$ware['supplier_id']){
				Show::warn(sprintf("材料'%s'没有选择供应商及报价"));
			}
			if(!$supplier_id){
				$supplier_id = $ware['supplier_id'];
			}
			elseif($supplier_id != $ware['supplier_id']){
				Show::warn('材料供应商冲突');
			}
			$total += ($ware['amount']*$ware['price']);
		}

		$supplier = Supplier::getFullName($supplier_id);

		$trans = Db::get('Indent')->trans();
		$trans->on();
		
		//修改采购订单
		$indent_id = fetch_a_int('indent_id');
		if($indent_id){
			$indent = $this->indentCanbeModify($indent_id);
			
			/*
			 * 修改汇总前的需求材料状态
			 */
			$ditems = DemandHelper::getItemsByIndent($indent_id);
			foreach($ditems as $demandid=>$items){
				Db::get('DemandItems')->update(array('state'=>2))->where(
						array('demand_id'=>$demandid), array('ware_id','IN',$items))->exec(0);
			}
			
			if(!IndentItems::deleteByIndent($indent_id)){
				$trans->rollback();
				Show::warn('删除旧材料记录失败');
			}
			if(!Indent::update($indent_id, array(
				'total'			=> $total,
				'audit_flow'	=> Reviewer::AUDIT_NONE,
				'supplier_id'	=> $supplier_id,
				'supplier'		=> $supplier,
				'pr_no'			=> FilterHelper::invert(fetch_a_string('pr_no')),
				'remark'		=> FilterHelper::sanitize(fetch_a_string('remark')),
				))){
					$trans->rollback();
					Show::warn('更新总记录失败');
			}
			if(!ReviewerHelper::backupAndClean(Reviewer::CLS_INDENT, $indent_id)){
				$trans->rollback();
				Show::warn('保存审批记录失败');
			}
		}
		else{
			//新建订单,记录入库
			$indent_id = Indent::add(array(
				'summary_id'	=> $id,
				'supplier_id'	=> $supplier_id,
				'supplier'		=> $supplier,
				'sno'			=> Sno::cgen('indent'),
				'addtime'		=> time(),
				'sum_month'		=> date('Ym'),
				'user_id'		=> UID,
				'dept_id'		=> $dept_id,
				'remark'		=> FilterHelper::sanitize(fetch_a_string('remark')),
				'total'			=> $total,
				'audit_flow'	=> 0,
				'back_flow'		=> 0,
				'pr_no'			=> FilterHelper::invert(fetch_a_string('pr_no')),
			));
			if(!$indent_id){
				$trans->rollback();
				Show::warn('新建订单失败');
			}
		}

		//保存订单明细（材料）
		foreach($wares as $ware){
			$r = IndentItems::add(array_merge(array(
					'indent_id'	=> $indent_id,
					'remark' => FilterHelper::sanitize(fetch_a_string($ware['ware_id'], $ware_remarks)),
					), $ware));
			if(!$r){
				$trans->rollback();
				Show::warn('添加订单条目失败.');
			}
		}
		//修改汇总材料明细状态
		SummaryItemsHelper::changeState($id, array('ware_id','IN',array_keys($wares)), DemandItems::STATE_INDENT);
		if(!$r){
			$trans->rollback();
			Show::warn('修改原材料记录状态失败');
		}

		//增加订单审批
		if(!ReviewerHelper::expand(Reviewer::CLS_INDENT, $indent_id, $dept_id)){
			$trans->rollback();
			Show::warn(ReviewerHelper::getLastError());
		}

		//检查材料状态，若都已生成订单，改变flow为1;
		//todo: 或除无法采购，其实材料都已生成订单，也改flow为1
		$_count = Db::get('SummaryItems')->count()
				->where("summary_id={$id} AND state<".DemandItems::STATE_INDENT)->getCol();
		if(0==$_count){
			Db::get('Summary')->update(array('flow'=>1))->where(array('id'=>$id))->exec();
		}
		
		$trans->commit();
		Show::note('保存订单成功', url("indent-view/id/{$indent_id}"));
	}

	/**
	 * 采购订单明细列表
	 */
	public function views(){
		$this->get_indent_list(array(
				'title' => '采购订单明细记录',
				'where' => null,
			));
	}

	/**
	 * 查看订单明细
	 */
	public function view(){
		$indent_id = fetch_a_int('id');
		if(!IndentHelper::hasPurview($indent_id)){
			Show::warn('无权操作', url('indent-views'));
		}

		$info = IndentHelper::getDetail($indent_id);
		if(!$info){
			Show::warn('Indent not found!', url('indent-views'));
		}
		#Debug::pre($info);
		$this->assign('indent', $info);
		$this->assign('reviewers', ReviewerHelper::getList(Reviewer::CLS_INDENT, $indent_id));
		$this->assign('reviewer_back', ReviewerHelper::getBackups(Reviewer::CLS_INDENT, $indent_id));
		$this->display();
	}

	/**
	 * 强制结单
	 */
	public function force(){
		if(fetch_a_int('id')){
			$info = IndentHelper::getDetail(fetch_a_int('id'));
			if(!$info){
				Show::warn('无此采购订单!', url('indent-views'));
			}
			$this->assign('indent', $info);
			$this->display();
		}
		else{
                    $this->get_indent_list(array(
				'title' => '采购订单列表（强制结单）',
				'where' => '(audit_flow=1 AND back_flow<2)',
				'opt' => array(array(
					'url' => url('indft/id/%d'),
					'class' => 'quote',
					'title' => '强制结单',
				)),
			));
		}
	}
	
	public function doForce(){
		$id = fetch_a_int('id');
		$type = fetch_a_int('type');
		$errmsg = '';
		if(IndentHelper::forceStop($id, $type, $errmsg)){
			Show::warn("操作成功.");
		}
		else{
			Show::warn("操作失败：".$errmsg);
		}
	}

	/** 取采购订单列表(公共函数) */
	protected function get_indent_list($args=array()){
		$where = ($args['where'] ? : '1');
		if($sno=fetch_a_string('sno')){
			$where .= ' AND sno LIKE "'.Db::qstr($sno).'%"';
		}
		if($spid=fetch_a_int('supplier_id')){
			$where .= " AND supplier_id={$spid}";
		}
                
		$pager = PagerHelper::split(IndentHelper::count($where));
		$this->assign('list', IndentHelper::getList($where, $pager['r_offset'], $pager['p_size']));
		$this->assign('args', $args);
		$this->assign('suppliers', Supplier::getList());
		$this->display('indent-views');
	}

}
?>
